package com.content.tinkhuyenmai;

import java.net.URL;
import java.util.List;

import com.db.Insert;
import com.util.Common;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

public class CatProduct {
	public static void main(String[] args) {
		try {
			CatProduct cp = new CatProduct();
			cp.getAllUrlCat("http://tinkhuyenmai.net");			
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.toString());
		}
	}
	
	/**
	 * get all cat in website tinkhuyenmai.vn insert or update to db protuct_cat
	 * @param mainUrl
	 */
	public void getAllUrlCat(String mainUrl){
		try {
			Insert ins = new Insert();
			String name=null;
			String catId1=null;
			String catId2=null;
			String catId3=null;
			String ext=null;
			
			List<Element> link1 = new Common().getAllUrl(mainUrl);
			//List<Element> link2 =null;
			List<Element> link3 =null;
				
			for (Element item : link1) {
				String href=item.getAttributeValue("href");
				if (href==null) continue;
				if(href.indexOf("Category.aspx?IDCat=")==0){
					//System.out.println(href);
					name=item.getContent().getTextExtractor().toString();
					catId1 = href.substring(href.indexOf("=")+1);
					ext = ins.insertCatProduct("0", name, "", catId1,new Process().ROOT_URL+"/"+href);
										
					System.out.println("update success cat 1!");
					List<Element> link2 = new Common().getAllUrl(new Process().ROOT_URL+"/"+href);
					for (Element item2 : link2) {
						//System.out.println(item2.getAttributeValue("href"));
						href=item2.getAttributeValue("href");
						if (href==null) continue;
						if(href.indexOf("Category.aspx?IDCat=")==0){
							name=item2.getContent().getTextExtractor().toString();
							catId2 = href.substring(href.indexOf("=")+1);
							ext = ins.insertCatProduct(catId1, name, "", catId2,new Process().ROOT_URL+"/"+href);
							
							System.out.println("update success cat 2!");
							link3 = new Common().getAllUrl(new Process().ROOT_URL+"/"+href);
							for (Element item3 : link3) {
								href=item3.getAttributeValue("href");
								if (href==null) continue;
								if(href.indexOf("Category.aspx?IDCat=")==0){
									name=item3.getContent().getTextExtractor().toString();
									catId3 = href.substring(href.indexOf("=")+1);
									ext = ins.insertCatProduct(catId2, name, "", catId3,new Process().ROOT_URL+"/"+href);
									if(!ext.equals("S001")) System.out.println(ext);
									else System.out.println("update success cat 3!");
								}
							}								
						}
					}
				}
				
			}
		
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.toString());
		}
	}
}
